りおんクロニクル


C#で作成するデスクトップアプリでホバー時に色が変化し、クリック時に震えるボタン

Home【2026年版】C# / .NET入門と実践ガイド|基礎・業務アプリ開発・SQLite連携まで体系的に解説

C#で作成するデスクトップアプリでホバー時に色が変化し、クリック時に震えるボタン

サンプルコード


using System;
using System.Drawing;
using System.Windows.Forms;

public class AnimatedButtonApp : Form
{
    private Button animatedButton;

    public AnimatedButtonApp()
    {
        // フォーム設定
        this.Text = "アニメーションボタン";
        this.Size = new Size(400, 300);

        // ボタン作成
        animatedButton = new Button
        {
            Text = "クリックしてみて!",
            Size = new Size(120, 40),
            Location = new Point(140, 110),
            BackColor = Color.Blue,
            ForeColor = Color.White
        };

        // ホバーイベント (色の変化)
        animatedButton.MouseEnter += (s, e) => animatedButton.BackColor = Color.DarkBlue;
        animatedButton.MouseLeave += (s, e) => animatedButton.BackColor = Color.Blue;

        // クリックイベント (震える動き)
        animatedButton.Click += (s, e) =>
        {
            // 震える動きを実現
            var originalLocation = animatedButton.Location;

            for (int i = 0; i < 5; i++)
            {
                animatedButton.Location = new Point(originalLocation.X - 5, originalLocation.Y);
                System.Threading.Thread.Sleep(50);
                animatedButton.Location = new Point(originalLocation.X + 5, originalLocation.Y);
                System.Threading.Thread.Sleep(50);
            }

            animatedButton.Location = originalLocation; // 元の位置に戻す
        };

        // フォームにボタンを追加
        this.Controls.Add(animatedButton);
    }

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new AnimatedButtonApp());
    }
}

    

追加説明

前のページ  次のページ